﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Media;
using Avalonia.Threading;
using AvaloniaApplication1.IServices;
using AvaloniaApplication1.Models;
using AvaloniaApplication1.Util;
using CommunityToolkit.Mvvm.Collections;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using MQTTnet;
using MQTTnet.Protocol;
using Newtonsoft.Json.Linq;
using SukiUI;

namespace AvaloniaApplication1.ViewModels.CardViewModel;


public partial class DataGridViewModel:ObservableObject
{
    private readonly IMqttDeviceManager _deviceManager;
    
    [ObservableProperty]
    private IBrush _background = CreateLightGradient();

    // [ObservableProperty]
    // private ObservableCollection<MqttMessageDataModel> _modbusData=new ();
    //声明UI数据源 
    [ObservableProperty]
    private ObservableCollection<ModbusData> _displayDeviceModbusData=new ();

    [ObservableProperty]
    private bool _mqttisconneted;
    
    public DataGridViewModel(IMqttDeviceManager deviceManager)
    {
        // 初始化DisplayDeviceModbusData集合
        DisplayDeviceModbusData = new ObservableCollection<ModbusData>();

        _deviceManager = deviceManager;
        _deviceManager.DeviceStatusChanged += OnDeviceStatusChanged;
        // _deviceManager.DeviceDataReceived += OnDeviceDataReceived;
        SukiTheme.GetInstance().OnBaseThemeChanged+= themeChanged =>
        {
            Background = themeChanged.Key.Equals("dark") ? CreateDarkGradient(): CreateLightGradient();
        };
  //     _  = InitializeMqttDevicesAsync();
    
    }
    private async Task InitializeMqttDevicesAsync()
    {
        // // 添加设备
        // await _deviceManager.AddDeviceAsync("device1", "172.16.2.22", 8630, "avatest", "home123", "modbus/test1");
        // await _deviceManager.AddDeviceAsync("device2", "172.16.2.22", 8630, "avatest1", "home123", "sensor/test2");
        //     
        // // 连接设备
        // await _deviceManager.ConnectDeviceAsync("device1");
        // await _deviceManager.ConnectDeviceAsync("device2");
        //     
        //
        // if (_deviceManager.IsDeviceConnected("device1")&& _deviceManager.IsDeviceConnected("device2"))
        // {
        //     Mqttisconneted=true;
        // }
    
    }
    // 添加连接切换命令
    [RelayCommand]
    private async Task ToggleDeviceConnectionAsync()
    {
        try
        {
            // 直接检查设备实际连接状态，而不是依赖Mqttisconneted属性
            bool isCurrentlyConnected = _deviceManager.IsDeviceConnected("device1") && _deviceManager.IsDeviceConnected("device2");

            if (isCurrentlyConnected)
            {
                // 断开连接
                AppLogger.Information("Disconnecting devices############");
                await _deviceManager.DisconnectDeviceAsync("device1");
                await _deviceManager.DisconnectDeviceAsync("device2");
            }
            else
            {
                // 重新连接
                await _deviceManager.ConnectDeviceAsync("device1");
                await _deviceManager.ConnectDeviceAsync("device2");
            }
        }
        catch (Exception ex)
        {
            AppLogger.Error(ex, "Failed to toggle device connection");
        }
        finally
        {
            // 确保在UI线程上更新状态
            Dispatcher.UIThread.InvokeAsync(() =>
            {
                Mqttisconneted = _deviceManager.IsDeviceConnected("device1") && _deviceManager.IsDeviceConnected("device2");
            });
        }
    }
    private void OnDeviceStatusChanged(object? sender, DeviceStatusEventArgs e)
    {
       //  // 更新UI中的设备状态
       // AppLogger.Information($"Device form DataGridViewModel-message {e.DeviceId} status changed to {e.IsConnected}");
       // // 使用Dispatcher确保在UI线程上更新属性
       // Dispatcher.UIThread.Invoke(() =>
       // {
       //     Mqttisconneted = _deviceManager.IsDeviceConnected("device1") && _deviceManager.IsDeviceConnected("device2");
       //     // 或者如果只关心单个设备状态:
       //     // Mqttisconneted = e.IsConnected;
       // });
       //  
    }

    private void OnDeviceDataReceived(object? sender, DeviceDataEventArgs e)
    {
      var deviceId=e.DeviceId;
      var payload = e.Payload;
      var topic = e.Topic;
        //解析后的数据
        if (e.MessageData.MessageType == "Modbus")
        {
            
            var modbusData = new ModbusData(
                e.MessageData.ParsedData.GetValueOrDefault("DeviceId", "N/A")?.ToString(),
                e.MessageData.ParsedData.GetValueOrDefault("BaudRate", "N/A").ToString(),
                e.MessageData.ParsedData.GetValueOrDefault("Temperature", "N/A").ToString(),
                e.MessageData.ParsedData.GetValueOrDefault("Humidity", "N/A").ToString()
            );
            // 使用Dispatcher确保在UI线程上更新数据
            Dispatcher.UIThread.InvokeAsync(() =>
            {
                DisplayDeviceModbusData.Add(modbusData);
                if (DisplayDeviceModbusData.Count > 10)
                {
                    DisplayDeviceModbusData.RemoveAt(0);
                }
            });  
        }
        
      // // 根据消息类型处理数据
      // switch (e.MessageData.MessageType)
      // {
      //     case "Modbus":
      //         HandleModbusData(e);
      //         break;
      //     case "Generic":
      //         HandleGenericData(e);
      //         break;
      //     default:
      //         HandleGenericData(e); // 默认也按通用数据处理
      //         break;
      // }

    }
 

 
    
    
    // 创建深色渐变
    private static IBrush CreateDarkGradient() => new LinearGradientBrush
    {
        StartPoint = new RelativePoint(0, 0, RelativeUnit.Relative),
        EndPoint = new RelativePoint(1, 1, RelativeUnit.Relative),
        GradientStops = new GradientStops
        {
            new GradientStop { Color = Colors.Gray, Offset = 0 },
            new GradientStop { Color = Color.FromRgb(204, 204, 255), Offset = 1 }
        }
    };
    // 创建亮色渐变
    private static IBrush CreateLightGradient() => new LinearGradientBrush
    {
        StartPoint = new RelativePoint(0, 0, RelativeUnit.Relative),
        EndPoint = new RelativePoint(1, 1, RelativeUnit.Relative),
        GradientStops = new GradientStops
        {
            new GradientStop { Color = Colors.White, Offset = 0 },
            new GradientStop { Color = Color.FromRgb(204, 204, 255), Offset = 1 }
        }
    };
}